package com.isyscore.os.metadata.config;

import com.google.common.collect.ImmutableList;
import com.isyscore.license.sdk.LicenseCurrentDescValid;
import com.isyscore.license.sdk.LicenseSDK;
import com.isyscore.os.metadata.service.DataSourceService;
import com.isyscore.os.metadata.constant.CommonConstant;
import kotlin.Unit;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author fjZheng
 * @version 1.0
 * @date 2020/12/16 11:38
 */
@Slf4j
@Component
public class LicenseSupport {

    @Getter
    volatile boolean init = false;


    @Resource
    private DataSourceService dataSourceService;


    /**
     *获取要验证的数据限制数量，并根据已使用的数量判断是否达到限制，达到返回false, 没达到返回true
     * @param id
     * 0    设备可连接的数量限制
     * 1    设备的种类数量限制
     * 2    设备⽹关的数量限制
     * 3    数据库主库的数量限制
     * 4    数据库从库的数量限制
     * 5    数据库外部连接的数量限制
     * 6    报表的数量限制
     * 7    API每秒调⽤的数量限制
     * 8    集群的机器数量限制
     * @return
     */

    public boolean checkLicenseValid(Integer id){
        List<Integer> ids = ImmutableList.of(id);
        List<Integer> results = LicenseSDK.queryLicenseDescription(ids);
        Integer limit = 0;
        if (CollectionUtils.isEmpty(results)) {
            // 没有设置限制数量
            return true;
        } else {
            limit = results.get(0);
            if (limit <= 0) {
                return true;
            }
        }
        Integer currentCount = 0;
        if (Objects.equals(id, CommonConstant.LICENSE_EXTERNAL_DATABASE)) {
            currentCount = dataSourceService.getOutDataSourceCount();
        }
        return limit - currentCount > 0;
    }


    @PostConstruct
    public void init() {
        LicenseSDK.init("isc-license-service", 9013, result -> {
            init = true;
            return Unit.INSTANCE;
        });
        if (!Optional.ofNullable(LicenseSDK.getLicenseDescriptionValid()).map(LicenseCurrentDescValid::getValid).orElse(false)) {
            log.warn("license 授权描述不合法");
        }
    }
}

